"""
HTTP客户端模块
"""
import json
import time
import requests
from requests.exceptions import RequestException
import allure
from ..config.env import current_config

class HttpClient:
    """HTTP客户端类，封装请求方法"""
    
    def __init__(self, base_url=None):
        """
        初始化HTTP客户端
        
        Args:
            base_url: API基础URL，默认使用配置中的BASE_URL
        """
        self.base_url = base_url or current_config.BASE_URL
        self.timeout = current_config.TIMEOUT
        self.session = requests.Session()
        # 设置默认请求头
        self.session.headers.update({
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        })
        # 如果有API密钥，添加到请求头
        if current_config.API_KEY:
            self.session.headers.update({
                'Authorization': f'Bearer {current_config.API_KEY}'
            })
    
    def _send_request(self, method, endpoint, **kwargs):
        """
        发送HTTP请求
        
        Args:
            method: HTTP方法（GET, POST, PUT, DELETE等）
            endpoint: API端点
            **kwargs: 请求参数
            
        Returns:
            Response对象
        """
        url = f"{self.base_url}{endpoint}"
        timeout = kwargs.pop('timeout', self.timeout)
        retry_times = kwargs.pop('retry_times', current_config.RETRY_TIMES)
        retry_interval = kwargs.pop('retry_interval', current_config.RETRY_INTERVAL)
        
        # 记录请求信息到Allure报告
        with allure.step(f"发送{method}请求到 {url}"):
            allure.attach(
                json.dumps(kwargs.get('json', {}), ensure_ascii=False, indent=2),
                name="请求数据",
                attachment_type=allure.attachment_type.JSON
            )
        
        # 重试机制
        for i in range(retry_times + 1):
            try:
                response = self.session.request(
                    method=method,
                    url=url,
                    timeout=timeout,
                    **kwargs
                )
                
                # 记录响应信息到Allure报告
                try:
                    response_json = response.json()
                    allure.attach(
                        json.dumps(response_json, ensure_ascii=False, indent=2),
                        name="响应数据",
                        attachment_type=allure.attachment_type.JSON
                    )
                except ValueError:
                    allure.attach(
                        response.text,
                        name="响应数据",
                        attachment_type=allure.attachment_type.TEXT
                    )
                
                return response
            except RequestException as e:
                if i < retry_times:
                    time.sleep(retry_interval)
                    continue
                raise e
    
    def get(self, endpoint, params=None, **kwargs):
        """
        发送GET请求
        
        Args:
            endpoint: API端点
            params: 查询参数
            **kwargs: 其他请求参数
            
        Returns:
            Response对象
        """
        return self._send_request('GET', endpoint, params=params, **kwargs)
    
    def post(self, endpoint, data=None, json=None, **kwargs):
        """
        发送POST请求
        
        Args:
            endpoint: API端点
            data: 表单数据
            json: JSON数据
            **kwargs: 其他请求参数
            
        Returns:
            Response对象
        """
        return self._send_request('POST', endpoint, data=data, json=json, **kwargs)
    
    def put(self, endpoint, data=None, json=None, **kwargs):
        """
        发送PUT请求
        
        Args:
            endpoint: API端点
            data: 表单数据
            json: JSON数据
            **kwargs: 其他请求参数
            
        Returns:
            Response对象
        """
        return self._send_request('PUT', endpoint, data=data, json=json, **kwargs)
    
    def delete(self, endpoint, **kwargs):
        """
        发送DELETE请求
        
        Args:
            endpoint: API端点
            **kwargs: 其他请求参数
            
        Returns:
            Response对象
        """
        return self._send_request('DELETE', endpoint, **kwargs) 